package cn.yangliu.init.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.date.DateNumberConverter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

/**
 * The type of ascii-jpa.
 *
 * <p>
 * .
 *
 * @author 杨柳
 */
public class LocalDateConverter implements Converter<LocalDate> {

    private static final DateNumberConverter converter = new DateNumberConverter();

    @Override
    public Class supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDate convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Date date = converter.convertToJavaData(cellData, contentProperty, globalConfiguration);
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    @Override
    public CellData convertToExcelData(LocalDate value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        ZonedDateTime zonedDateTime = value.atStartOfDay(ZoneId.systemDefault());
        Date date = Date.from(zonedDateTime.toInstant());
        return converter.convertToExcelData(date, contentProperty, globalConfiguration);
    }
}
